package com.wyk.service.impl;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.wyk.service.PaymentService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @author WangYuKai
 * @Date 2022/6/23
 * @apiNote
 */
@Service
public class PaymentServiceImpl implements PaymentService {
    @Override
    public String paymentOk(Integer id) {
        return "线程池：" + Thread.currentThread().getName() +" \t paymentOk,id" + id +"哈哈哈哈哈";
    }
    /**
     * 访问超时，演示降级(服务降级)
     * fallbackMethod:回退方法
     */
    @Override
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",
            commandProperties ={@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value="30000")} )
    public String paymentError(Integer id) {
        int timeOut = 2;
        try{TimeUnit.SECONDS.sleep(timeOut);}catch (InterruptedException e){e.printStackTrace();};
        return "线程池：" + Thread.currentThread().getName() +" \t paymentError,id" + id +"呜呜呜呜 + 耗时：" + timeOut;
    }

    public String paymentInfo_TimeOutHandler(Integer id){
        return "调用支付接口超时" + "\t" + "线程池的名字叫做：" + Thread.currentThread().getName() + "当前id" + id;
    }

    //------------------------------服务熔断-------------------------------------

    /**
     * 类似于兜底的方案，只不过又嵌套了一层而已
     */
    @HystrixCommand(defaultFallback = "paymentCiruitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindownInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThesholdPercentage",value = "60")//失败率打到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id")Integer id){
        if(id < 0){
            throw new RuntimeException("id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();//生成id
        return Thread.currentThread().getName() + " \t" + "调用成功：id是：" + serialNumber;
    }

    public String paymentCiruitBreaker_fallback(@PathVariable("id")Integer id){
        return "id 不能为负数" + id;
    }

}
